package cn.mujiankeji.mbrowser.界面.标签页.主页

import android.annotation.SuppressLint
import android.widget.Space
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.detectVerticalDragGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cn.mujiankeji.mbrowser.工具.clickable2
import cn.mujiankeji.mbrowser.数据.数据库.DBHomeTab
import cn.mujiankeji.mbrowser.界面.图标.MyIconPack
import cn.mujiankeji.mbrowser.界面.图标.myiconpack.扫码
import kotlinx.coroutines.launch
import cn.mujiankeji.mbrowser.app.应用组件.应用图片
import cn.mujiankeji.mbrowser.工具.JSON
import cn.mujiankeji.mbrowser.工具.mlog
import cn.mujiankeji.mbrowser.数据.配置项.应用配置
import cn.mujiankeji.mbrowser.界面.图标.myiconpack.关闭填充
import cn.mujiankeji.mbrowser.界面.图标.myiconpack.加
import cn.mujiankeji.mbrowser.界面.图标.myiconpack.菜单
import cn.mujiankeji.mbrowser.界面.图标.myiconpack.设置
import cn.mujiankeji.mbrowser.界面.小窗页.文本编辑窗口状态
import cn.mujiankeji.mbrowser.界面.组件.按钮.水平标签
import cn.mujiankeji.mbrowser.界面.组件.配置列表.配置行
import cn.mujiankeji.mbrowser.界面.组件.配置列表.配置行_拖动条
import cn.mujiankeji.mbrowser.界面.组件.配置列表.配置行_选项
import io.github.vinceglb.filekit.FileKit
import io.github.vinceglb.filekit.PlatformFile
import io.github.vinceglb.filekit.copyTo
import io.github.vinceglb.filekit.dialogs.FileKitMode
import io.github.vinceglb.filekit.dialogs.FileKitType
import io.github.vinceglb.filekit.dialogs.openFilePicker
import io.github.vinceglb.filekit.extension
import io.github.vinceglb.filekit.name
import kotlinx.coroutines.flow.first

@SuppressLint("UseOfNonLambdaOffsetOverload")
@Composable
fun 主页标签实现(state: 主页标签状态) {

    val coroutineScope = rememberCoroutineScope()
    state.coroutine = coroutineScope
    DisposableEffect(Unit) {
        onDispose {
            state.coroutine = null
        }
    }
    LaunchedEffect(Unit) {
        state.加载标签()
    }
    LaunchedEffect(Unit) {
        应用配置.读取主页样式().collect{
            if (it.isNotEmpty()){
                try {
                    JSON.decodeFromString<主页样式配置项目>(it).let {
                        state.主页样式 = it
                    }
                }catch (e : Exception){
                    // e.printStackTrace()
                }
            }

        }
    }

    // 下拉刷新状态
    var 下拉距离 by remember { mutableStateOf(0f) }
    val 下拉阈值 = 150f // 触发刷新的阈值
    val 搜索框偏移 by animateFloatAsState(
        targetValue = minOf(下拉距离 * 0.5f, 下拉阈值 * 0.5f),
        animationSpec = tween(durationMillis = 300)
    )
    val 标签透明度 by animateFloatAsState(
        targetValue = maxOf(1f - (下拉距离 / 下拉阈值) * 0.5f, 0.5f),
        animationSpec = tween(durationMillis = 300)
    )
    
    val 是否正在下拉 = 下拉距离 > 0f
    ModalNavigationDrawer(drawerState = state.抽屉状态,
        drawerContent = {
        主题样式配置(state)
    },
        gesturesEnabled = state.编辑模式) {
        Scaffold(containerColor = MaterialTheme.colorScheme.surface) {
            Box(Modifier.padding(it).fillMaxSize()
                .pointerInput(Unit){
                    detectVerticalDragGestures(
                        onDragStart = { },
                        onDragEnd = {
                            if (下拉距离 >= 下拉阈值) {
                                // 触发下拉刷新
                                coroutineScope.launch {
                                    state.响应下滑()
                                }
                            }
                            // 重置下拉距离
                            下拉距离 = 0f
                        },
                        onDragCancel = {
                            下拉距离 = 0f
                        },
                        onVerticalDrag = { change, dragAmount ->
                            change.consume()
                            // 只允许向下拖动
                            if (dragAmount > 0) {
                                下拉距离 += dragAmount
                            } else if (下拉距离 > 0) {
                                下拉距离 = maxOf(0f, 下拉距离 + dragAmount)
                            }
                        }
                    )
                })
            {
                Column(modifier = Modifier.fillMaxSize()) {
                    // 上 logo
                    Column(
                        Modifier
                            .fillMaxWidth()
                            .weight(1f)
                    ) {
                        Box(Modifier.weight(1f)){
                            if (state.编辑模式){
                                IconButton({state.coroutine?.launch {
                                    state.抽屉状态.open()
                                }}, modifier = Modifier.padding(5.dp)) {
                                    Icon(MyIconPack.菜单,"",
                                        modifier = Modifier.size(22.dp))
                                }
                            }
                        }
                        Logo()
                    }

                    // 下 搜索框 标签列表
                    Column(
                        Modifier
                            .fillMaxWidth()
                            .weight(1.5f)
                            .offset(y = with(LocalDensity.current) { 搜索框偏移.toDp() })
                            .alpha(标签透明度)
                    ) {
                        搜索框视图(state)
                        标签列表视图(state = state)
                        if (state.编辑模式){
                            Button({state.编辑模式 = false}, modifier = Modifier.align(Alignment.CenterHorizontally)) {
                                Text("完成")
                            }
                        }
                    }
                }

                // 显示下拉刷新指示器
                if (是否正在下拉) {
                    val 刷新进度 = (下拉距离 / 下拉阈值).coerceIn(0f, 1f)
                    Box(
                        modifier = Modifier
                            .align(Alignment.TopCenter)
                            .padding(top = 16.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator(
                            progress = { 刷新进度 },
                            modifier = Modifier.size(40.dp),
                            strokeWidth = 3.dp
                        )
                    }
                }
            }

        }
    }


}

@Composable
private fun 搜索框视图(state: 主页标签状态) {
    Row(
        Modifier
            .padding(horizontal = 20.dp, vertical = 20.dp)
            .fillMaxWidth()
            .height(50.dp)
            .border(
                1.dp, MaterialTheme.colorScheme.secondary,
                MaterialTheme.shapes.medium
            )
            .padding(horizontal = 5.dp)
            .clickable2 {
                state.进入搜索()
            },
        verticalAlignment = Alignment.CenterVertically
    ) {
        Icon(
            Icons.Default.Search,
            contentDescription = "搜索",
            modifier = Modifier.padding(start = 8.dp),
            tint = MaterialTheme.colorScheme.onSurfaceVariant
        )
        
        Text(
            "搜索或输入网址",
            color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f),
            modifier = Modifier
                .weight(1f)
                .padding(horizontal = 8.dp)
        )

        // 二维码
        IconButton({ state.进入扫码页() }) {
            Icon(
                MyIconPack.扫码, "扫码",
                modifier = Modifier.size(18.dp)
            )
        }
    }
}



@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun ColumnScope.标签列表视图(state : 主页标签状态
) {
    val gridState = rememberLazyGridState()

    val 标签字体大小 = state.主页样式.标签字体大小.sp
    val 标签图标大小 = state.主页样式.标签图标大小.dp
    val 标签圆角 = RoundedCornerShape(state.主页样式.标签圆角)
    LazyVerticalGrid(
        columns = GridCells.Adaptive(70.dp),
        contentPadding = PaddingValues(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp),
        horizontalArrangement = Arrangement.spacedBy(16.dp),
        state = gridState,
        modifier = Modifier.fillMaxWidth().weight(1f)
    ) {
        // 显示标签项目
        itemsIndexed(state.标签列表) { index, item ->
            标签项目(state,item,
                标签圆角 = 标签圆角,
                标签图标大小 = 标签图标大小,
                标签字体大小 = 标签字体大小)
        }

        if (state.编辑模式 || state.标签列表.size == 0){
            item {
                添加标签的标签(
                    state,
                    标签圆角 = 标签圆角,
                    标签图标大小 = 标签图标大小,
                    标签字体大小 = 标签字体大小
                )
            }
        }


    }
}

@Composable
private fun 标签项目(state : 主页标签状态,item : DBHomeTab,
                     标签圆角 : RoundedCornerShape,
                     标签图标大小 : Dp,
                     标签字体大小 : TextUnit){
    Row(
        modifier = Modifier.size(75.dp)
            .clip(标签圆角)
            .combinedClickable(
                onClick = {
                    if (!state.编辑模式) state.打开(item)
                    else {
                        state.请求编辑项目(item)
                    }
                },
                onLongClick = {
                    if (!state.编辑模式) {
                        state.编辑模式 = true
                    }
                }),
        verticalAlignment = Alignment.CenterVertically
    ){
        Column(Modifier.fillMaxWidth(),
            horizontalAlignment = Alignment.CenterHorizontally) {

            Box(Modifier.size(标签图标大小))
            {
                应用图片(item.图标路径, modifier = Modifier.fillMaxSize())
                if (state.编辑模式){
                    IconButton({
                        state.删除标签(item.id)
                    }, modifier = Modifier.size(16.dp)
                        .align(Alignment.TopEnd)) {
                        Icon(MyIconPack.关闭填充,"",
                            tint = MaterialTheme.colorScheme.secondary,
                            modifier = Modifier.size(15.dp))
                    }
                }
            }

            Spacer(Modifier.height(10.dp))

            Text(item.标签名称, style = MaterialTheme.typography.labelSmall,
                fontSize = 标签字体大小,
                maxLines = 1,
            )

        }
    }
}

@Composable
private fun 添加标签的标签(state: 主页标签状态,
                           标签圆角 : RoundedCornerShape,
                           标签图标大小 : Dp,
                           标签字体大小 : TextUnit){

    Row(
        modifier = Modifier.size(75.dp)
            .clickable {
                state.请求创建项目()
            },
        verticalAlignment = Alignment.CenterVertically
    ){
        Column(Modifier.fillMaxWidth(),
            horizontalAlignment = Alignment.CenterHorizontally) {

            Icon(MyIconPack.加,"添加标签",
                tint = MaterialTheme.colorScheme.secondary,
                modifier = Modifier.size(标签图标大小 - 3.dp))

            Spacer(Modifier.height(10.dp))

            Text(" ", style = MaterialTheme.typography.labelSmall,
                maxLines = 1,
                fontSize = 标签字体大小
            )

        }
    }

}



@Composable
private fun ColumnScope.Logo() {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(bottom = 20.dp),
        contentAlignment = Alignment.Center
    ) {

        Text(
            "M浏览器",
            style = MaterialTheme.typography.headlineMedium,
            color = MaterialTheme.colorScheme.primary
        )
    }
}

@Composable
private fun 主题样式配置(state : 主页标签状态){

    @Composable
    fun title(t : String) {
        Text(t, modifier = Modifier.padding(horizontal = 10.dp,22.dp),
            style = MaterialTheme.typography.titleSmall)
    }
    @Composable
    fun RowScope.tab(t : String,sel : Boolean,clickable : ()->Unit){
        FilterChip(sel,
            modifier =  Modifier.weight(1f)
                .padding(horizontal = 10.dp)
                .fillMaxHeight(),
            onClick = {clickable()},
            label = {
                Text(t, style = MaterialTheme.typography.bodyMedium,
                    textAlign = TextAlign.Center,
                    color = MaterialTheme.colorScheme.onSurface,
                    modifier = Modifier.fillMaxWidth())
            })

    }

    @Composable
    fun line(){
        Spacer(Modifier
            .padding(top = 10.dp)
            .fillMaxWidth().height(1.dp)
            .background(MaterialTheme.colorScheme.secondary))
    }

    Column(Modifier.fillMaxWidth(0.8f).fillMaxHeight()
        .background(MaterialTheme.colorScheme.surface)
        .verticalScroll(rememberScrollState(),true)) {

        Box(Modifier.fillMaxWidth()
            .padding(top = 55.dp)
            .height(60.dp),
            contentAlignment = Alignment.Center){
            Text("首页定制", style = MaterialTheme.typography.titleMedium)
        }

        line()

        // 背景
        title("背景")

        // 无 图片 颜色
        Row(Modifier.padding(vertical = 10.dp).fillMaxWidth().height(35.dp)){
           tab("无",state.主页样式.背景色 == null && state.主页样式.背景图片 == null) {
               state.主页样式.背景色 = null
               state.主页样式.背景图片 = null
               state.保存样式()
           }

            tab("图片",state.主页样式.背景图片 != null) {
                state.coroutine?.launch {
                    state.主页样式.背景色 = null
                    val file = FileKit.openFilePicker(FileKitType.Image, mode = FileKitMode.Single)
                    if (file != null){
                        mlog("filename",file.name,file.extension)
                        // file.copyTo(PlatformFile(应用配置.路径_数据 + file.name))
                        // todo
                    }

                    state.保存样式()
                }
            }

            tab("颜色",state.主页样式.背景色 != null) {
                // todo 颜色选择器
            }
        }

        line()

        // logo
        title("LOGO")
        Row(Modifier.padding(vertical = 10.dp).fillMaxWidth().height(35.dp)){
            tab("图片",state.主页样式.LOGO图标 != null) {
                // todo 文件选择
            }

            tab("文字",state.主页样式.LOGO文字 != null) {
                state.coroutine?.launch {
                    文本编辑窗口状态(state.主页样式.LOGO文字 ?:"",{"LOGO文本"})
                    {
                        it?.let {
                            state.主页样式.背景色 = null
                            state.主页样式.LOGO文字 = it
                            state.保存样式()
                        }
                    }
                }
            }

            tab("无",state.主页样式.LOGO文字 == null && state.主页样式.LOGO图标 == null) {
                state.主页样式.LOGO图标 = null
                state.主页样式.LOGO文字 = null
                state.保存样式()
            }
        }

        // 宽度
        配置行_拖动条("宽度", def = state.主页样式.LOGO宽度,10,310){
            state.主页样式.LOGO宽度 = it
            state.保存样式()
             "${it}dp"
        }
        配置行_拖动条("高度", def = state.主页样式.LOGO高度,10,200){
            state.主页样式.LOGO高度 = it
            state.保存样式()
            "${it}dp"
        }

        line()
        title("搜索框")

        配置行_拖动条("边框粗细", def = state.主页样式.搜索框粗细,0,10){
            state.主页样式.搜索框粗细 = it
            state.保存样式()
            "${it}dp"
        }
        配置行_拖动条("透明度", def = state.主页样式.搜索框透明度,0,100){
            state.主页样式.搜索框透明度 = it
            state.保存样式()
            "${it}%"
        }
        配置行_拖动条("圆角", def = state.主页样式.搜索框圆角,0,100){
            state.主页样式.搜索框圆角 = it
            state.保存样式()
            "${it}%"
        }
        配置行_拖动条("高度", def = state.主页样式.搜索框高度,0,90){
            state.主页样式.搜索框高度 = it
            state.保存样式()
            "${it}dp"
        }

        line()
        title("项目标签")
        配置行_拖动条("图标大小", def = state.主页样式.标签图标大小,10,60){
            state.主页样式.标签图标大小 = it
            state.保存样式()
            "${it}dp"
        }
        配置行_拖动条("字体大小", def = state.主页样式.标签字体大小,8,60){
            state.主页样式.标签字体大小 = it
            state.保存样式()
            "${it}sp"
        }
        配置行_拖动条("圆角", def = state.主页样式.标签圆角,0,100){
            state.主页样式.标签圆角 = it
            state.保存样式()
            "${it}%"
        }

        line()
        Spacer(Modifier.height(22.dp))

        Text("恢复默认配置",
            style = MaterialTheme.typography.titleSmall,
            textAlign = TextAlign.Center,
            modifier = Modifier.fillMaxWidth()
                .clickable {
                    state.coroutine?.launch {
                        应用配置.设置主页样式("")
                        state.主页样式 = 主页样式配置项目()
                    }
                })

        Spacer(Modifier.height(66.dp))

    }

}


